<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import DataTable from '../components/common/FyyDataTable1.vue'

// 创建axios实例，配置baseURL和超时
const api = axios.create({
  baseURL: '/api', // 对应Spring Boot后端的API路径
  timeout: 10000
})

// 状态管理
const tableData = ref([])
const loading = ref(false)
const error = ref(null)

// 分页和查询参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100]
})

const queryParams = reactive({
  houseNumber: '',
  status: '',
  // 添加其他可能的查询参数
})

// 列配置（保持不变）
const columns = [
  { prop: 'houseNumber', label: '房号', width: 120 },
  { prop: 'area', label: '面积', width: 100 },
  { prop: 'layout', label: '户型', width: 100 },
  { prop: 'floor', label: '楼层', width: 80 },
  { prop: 'unit', label: '单元', width: 80 },
  { 
    prop: 'status', 
    label: '状态', 
    type: 'status',
    statusMap: {
      'in': { label: '已入住', type: 'success' },
      'out': { label: '未入住', type: 'info' }
    }
  },
  { prop: 'ownerId', label: '业主关联ID', width: 120 },
  {
    prop: 'details', 
    label: '详细信息',
    slot: 'details'
  }
]

// 获取房屋列表（与Spring Boot后端交互）
const fetchHouses = async (page = 1, size = 10) => {
  loading.value = true
  error.value = null
  
  try {
    // 构建查询参数
    const params = {
      page: page - 1, // Spring Data默认页码从0开始
      size: size,
      ...queryParams // 包含其他查询参数
    }
    
    const response = await api.get('/houses', { params })
    
    // 假设Spring Boot后端返回Page对象格式
    tableData.value = response.data.content || []
    pagination.total = response.data.totalElements || 0
    pagination.currentPage = page
    pagination.pageSize = size
    
    return response.data
  } catch (err) {
    error.value = err.response?.data?.message || '获取房屋数据失败'
    console.error('获取房屋列表错误:', err)
  } finally {
    loading.value = false
  }
}

// 添加房屋
const handleRowAdd = async (newHouse) => {
  try {
    const response = await api.post('/houses', newHouse)
    tableData.value.unshift(response.data) // 添加到表格顶部
    showSuccessToast('房屋添加成功')
    return true
  } catch (err) {
    error.value = err.response?.data?.message || '添加失败'
    showErrorToast(error.value)
    return false
  }
}

// 编辑房屋
const handleRowEdit = async (updatedHouse) => {
  try {
    await api.put(`/houses/${updatedHouse.id}`, updatedHouse)
    
    // 更新本地数据
    const index = tableData.value.findIndex(item => item.id === updatedHouse.id)
    if (index !== -1) {
      tableData.value[index] = { ...updatedHouse }
    }
    
    showSuccessToast('房屋信息更新成功')
    return true
  } catch (err) {
    error.value = err.response?.data?.message || '更新失败'
    showErrorToast(error.value)
    return false
  }
}

// 删除房屋
const handleRowDelete = async (house) => {
  if (!window.confirm(`确定删除 ${house.houseNumber} 吗？`)) {
    return false
  }
  
  try {
    await api.delete(`/houses/${house.id}`)
    
    // 从本地数据移除
    tableData.value = tableData.value.filter(item => item.id !== house.id)
    showSuccessToast('房屋信息已删除')
    return true
  } catch (err) {
    error.value = err.response?.data?.message || '删除失败'
    showErrorToast(error.value)
    return false
  }
}

// 分页变化处理
const handlePageChange = (page) => {
  fetchHouses(page, pagination.pageSize)
}

const handleSizeChange = (size) => {
  fetchHouses(pagination.currentPage, size)
}

// 搜索功能
const handleSearch = () => {
  fetchHouses() // 从第一页开始搜索
}

// 重置搜索
const handleReset = () => {
  // 重置查询参数
  queryParams.houseNumber = ''
  queryParams.status = ''
  
  fetchHouses()
}

// 模拟提示框（实际项目应替换为UI库的toast组件）
const showSuccessToast = (message) => {
  console.log('[Success]', message)
  // 示例: this.$message.success(message)
}

const showErrorToast = (message) => {
  console.log('[Error]', message)
  // 示例: this.$message.error(message)
}

// 初始化加载
onMounted(() => {
  fetchHouses()
})
</script>

<template>
  <div class="property-fee-container">
    <div class="page-header bg-white p-4 rounded-lg shadow-sm mb-4">
      <h1 class="text-xl font-bold text-gray-800">业主名下的房屋信息</h1>
      
      <!-- 搜索表单 -->
      <div class="mt-4 flex flex-wrap gap-4">
        <el-form-item label="房号">
          <el-input 
            v-model="queryParams.houseNumber" 
            placeholder="请输入房号" 
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select 
            v-model="queryParams.status" 
            placeholder="请选择状态" 
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="已入住" value="in" />
            <el-option label="未入住" value="out" />
          </el-select>
        </el-form-item>
        
        <div class="flex items-end">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>
      
      <div v-if="error" class="mt-2 text-red-500">{{ error }}</div>
    </div>
    
    <div class="data-table-wrapper bg-white p-4 rounded-lg shadow-sm">
      <DataTable
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @row-add="handleRowAdd"
        @row-edit="handleRowEdit"
        @row-delete="handleRowDelete"
        @page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #details="{ row }">
          <span>{{ row.details }}</span>
        </template>
      </DataTable>
    </div>
  </div>
</template>

<style scoped>
.property-fee-container {
  min-height: 100%;
}

.data-table-wrapper {
  overflow: auto;
}
</style>